// import { message as Message } from "antd";
import axios from "axios";

// 创建 axios 实例
const axiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASEURL,
  timeout: import.meta.env.VITE_APP_TIMEOUT,
  headers: { "Content-Type": "application/json;charset=utf-8" },
});

// 请求拦截
axiosInstance.interceptors.request.use(
  config => {
    // 在请求被发送之前做些什么
    config.headers.Authorization = "Bearer Token";
    return config;
  },
  error => {
    // 请求错误时做些什么
    return Promise.reject(error);
  }
);

// 响应拦截
axiosInstance.interceptors.response.use(
  res => {
    if (!res.data) throw new Error("返回数据为空");

    const { status, data, message } = res.data;
    // 业务请求成功
    const hasSuccess = data && Reflect.has(res.data, "status") && status === 0; //0 表示成功
    if (hasSuccess) {
      return data;
    }
    // 业务请求错误
    // Message.error(message || "业务请求错误");
  },
  error => {
    const { response, message } = error || {};

    let errMsg = "";
    try {
      errMsg = response?.data?.message || message;
    } catch (error) {
      throw new Error(error);
    }
    // Message.error(errMsg);
    return Promise.reject(error);
  }
);

class APIClient {
  get(config) {
    return this.request({ ...config, method: "GET" });
  }

  post(config) {
    return this.request({ ...config, method: "POST" });
  }

  put(config) {
    return this.request({ ...config, method: "PUT" });
  }

  delete(config) {
    return this.request({ ...config, method: "DELETE" });
  }

  request(config) {
    return new Promise((resolve, reject) => {
      axiosInstance
        .request(config)
        .then(res => {
          resolve(res);
        })
        .catch(e => {
          reject(e);
        });
    });
  }
}
export default new APIClient();
